package com.info.zhiduoduo.admin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.evaluate.QueryEvaluateNoticeFrombean;
import com.info.zhiduoduo.admin.model.formbean.evaluate.SaveEvaluateNoticeFormBean;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.NotificationConfig;
import com.info.zhiduoduo.common.configs.WhetherTestConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.core.service.WxCrowdsourceMessageService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.wxmessage.WxTaxerWxMessageServiceImpl;
import com.info.zhiduoduo.repository.dto.evaluate.EvaluateNoticeInfoDto;
import com.info.zhiduoduo.repository.entity.evaluate.EvaluateNotice;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.evaluate.EvaluateNoticeMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

@Service
public class EvaluateNoticeService extends BaseService {

	@Resource
	MakerMapper makerMapper;

	@Resource
	CompanyMapper companyMapper;

	@Resource
	CrowdsourceAccountMapper crowdsourceAccountMapper;

	@Resource
	PartnerMapper partnerMapper;

	@Resource
	WxMessageService wxMessageService;

	@Resource
	WxPartnerMessageService wxPartnerMessageService;

	@Resource
	WxTaxerWxMessageServiceImpl wxTaxerWxMessageService;

	@Resource
	WxCrowdsourceMessageService wxCrowdsourceMessageService;

	@Resource
	CommonConfig commonConfig;

	@Resource
	WhetherTestConfig whetherTestConfig;

	@Resource
	NotificationConfig notificationConfig;

	@Resource
	EvaluateNoticeMapper evaluateNoticeMapper;

	public SmartResult saveEvaluateNotice(BaseSimpleFormBean<SaveEvaluateNoticeFormBean> formBean){
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getUserid()) {
			return errorParamSmartResult();
		}
		SaveEvaluateNoticeFormBean noticeFormBean = formBean.getReqdata();
		EvaluateNotice notice = new EvaluateNotice()
				.setEvaluateTitle(noticeFormBean.getEvaluateTitle())
				.setEvaluateContent(noticeFormBean.getEvaluateContent())
				.setSenderType(noticeFormBean.getSenderType())
				.setFounder(formBean.getUserid());
		if (!notice.insert()) {
			return smartResult(StatusMsg.StatusMsg_199);
		}
		//增加测试环境
		if (whetherTestConfig.isTest()) {
			LogUtil.info("测试环境-新建并发送评价公告");
			//构建跳转链接
			String url = String.format(commonConfig.getZddEvaluateUrl(), 178, 5, 1, notice.getId());
			//调用 公众号公告通知(一定带链接)
			wxMessageService.sendSurveyNotice(notice.getEvaluateTitle(), notice.getEvaluateContent(), url, "oB8CR0SpZRdPAD67vRLAnuadWjus");
			return smartResult();
		}
		//1. 公众号 (通知对象：所有企业， 创客+测试组)
		Set<EvaluateNoticeInfoDto> zhiDuoDuoSet = new HashSet<>();
		//2.合伙人公众号（通知对象：合伙人）
		Set<EvaluateNoticeInfoDto> partnerSet = new HashSet<>();
		//3.智杰祱公众号（通知对象:智杰祱创客）
		Set<EvaluateNoticeInfoDto> taxerSet = new HashSet<>();
		//4.智众包公众号（通知对象:智众包创客+自然人）
		Set<EvaluateNoticeInfoDto> crowdSourceSet = new HashSet<>();

		//发送人：1.企业+创客，2.所有企业，3.众包企业，4. 企业，5.所有创客，6. 创客，7. 创客，8.众包创客，9.自然人，10.合伙人，11.测试组
		if (1 == noticeFormBean.getSenderType()) {
			//所有企业
			List<EvaluateNoticeInfoDto> allCompany = companyMapper.getPushEvaluateNoticeNeedData(0);
			// 创客
			List<EvaluateNoticeInfoDto> zddMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.INTELL);
			//智众包创客
			List<EvaluateNoticeInfoDto> crowdSourceMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.CROWDSOURCE);
			//智杰祱创客
			List<EvaluateNoticeInfoDto> taxerMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.TAXER);

			zhiDuoDuoSet.addAll(allCompany);
			zhiDuoDuoSet.addAll(zddMaker);
			crowdSourceSet.addAll(crowdSourceMaker);
			taxerSet.addAll(taxerMaker);

		} else if (2 == noticeFormBean.getSenderType()) {
			//所有企业
			List<EvaluateNoticeInfoDto> allCompany = companyMapper.getPushEvaluateNoticeNeedData(0);

			zhiDuoDuoSet.addAll(allCompany);

		} else if (3 == noticeFormBean.getSenderType()) {
			//智众包企业
			List<EvaluateNoticeInfoDto> crowdSourceCompany = companyMapper.getPushEvaluateNoticeNeedData(2);

			crowdSourceSet.addAll(crowdSourceCompany);

		} else if (4 == noticeFormBean.getSenderType()) {
			// 企业
			List<EvaluateNoticeInfoDto> zddCompany = companyMapper.getPushEvaluateNoticeNeedData(1);

			zhiDuoDuoSet.addAll(zddCompany);

		} else if (5 == noticeFormBean.getSenderType()) {
			// 创客
			List<EvaluateNoticeInfoDto> zddMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.INTELL);
			//智众包创客
			List<EvaluateNoticeInfoDto> crowdSourceMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.CROWDSOURCE);
			//智杰祱创客
			List<EvaluateNoticeInfoDto> taxerMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.TAXER);

			zhiDuoDuoSet.addAll(zddMaker);
			crowdSourceSet.addAll(crowdSourceMaker);
			taxerSet.addAll(taxerMaker);

		} else if (6 == noticeFormBean.getSenderType()) {
			// 创客
			List<EvaluateNoticeInfoDto> zddMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.INTELL);

			zhiDuoDuoSet.addAll(zddMaker);

		} else if (7 == noticeFormBean.getSenderType()) {
			//智杰祱创客
			List<EvaluateNoticeInfoDto> taxerMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.TAXER);

			taxerSet.addAll(taxerMaker);

		} else if (8 == noticeFormBean.getSenderType()) {
			//智众包创客
			List<EvaluateNoticeInfoDto> crowdSourceMaker = makerMapper.getPushEvaluateNoticeNeedData(MakerType.CROWDSOURCE);

			crowdSourceSet.addAll(crowdSourceMaker);

		} else if (9 == noticeFormBean.getSenderType()) {
			//自然人
			List<EvaluateNoticeInfoDto> crowdSourceNaturalPerson = crowdsourceAccountMapper.getPushEvaluateNoticeNeedData();

			zhiDuoDuoSet.addAll(crowdSourceNaturalPerson);

		} else if (10 == noticeFormBean.getSenderType()) {
			//合伙人
			List<EvaluateNoticeInfoDto> partners = partnerMapper.getPushEvaluateNoticeNeedData();

			partnerSet.addAll(partners);

		} else if (11 == noticeFormBean.getSenderType()) {
			//测试组
			List<String> testList = notificationConfig.getTestNoticeOpenids();
			//构建数据
			testList.forEach(data -> {
				Maker maker = new Maker().selectOne(Condition.create().eq("openid",data).or().eq("taxer_openid",data));
				if (null != maker) {
					EvaluateNoticeInfoDto dto = new EvaluateNoticeInfoDto();
					dto.setUserId(maker.getUserid()).setOpenId(data);
					//创客类型：1：  2：  3:智众包创客
					if (2 == maker.getMakerType()) {
						dto.setUserType(5);
						taxerSet.add(dto);
					} else if (3 == maker.getMakerType()) {
						dto.setUserType(6);
						crowdSourceSet.add(dto);
					} else {
						dto.setUserType(1);
						zhiDuoDuoSet.add(dto);
					}
				}
			});
		} else {
			return smartResult(StatusMsg.StatusMsg_804);
		}

		if (!CollectionUtils.isEmpty(zhiDuoDuoSet)) {
			pushNotice(zhiDuoDuoSet, 1, notice);
		}
		if (!CollectionUtils.isEmpty(partnerSet)) {
			pushNotice(partnerSet, 2, notice);
		}
		if (!CollectionUtils.isEmpty(taxerSet)) {
			pushNotice(taxerSet, 3, notice);
		}
		if (!CollectionUtils.isEmpty(crowdSourceSet)) {
			pushNotice(crowdSourceSet, 4, notice);
		}

		return smartResult(notice.getId());
	}

	/**
	 * 调用公告通知方法
	 * @param infoDtoList 发送人所需数据集合
	 * @param type 通知类型：1. 公众号，2.合伙人公众号，3.智杰祱公众号，4.智众包公众号
	 */
	private void pushNotice(Set<EvaluateNoticeInfoDto> infoDtoList, int type, EvaluateNotice notice){
		infoDtoList.forEach(infoDto -> {
			if(StringUtils.isBlank(infoDto.getOpenId())){
				return;
			}
			//构建跳转链接
			String url = String.format(commonConfig.getZddEvaluateUrl(), infoDto.getUserId(), infoDto.getUserType(), 1, notice.getId());
			if (1 == type) {
				//调用 公众号公告通知(一定带链接)
				wxMessageService.sendSurveyNotice(notice.getEvaluateTitle(), notice.getEvaluateContent(), url, infoDto.getOpenId());
			} else if (2 == type) {
				//调用合伙人公众号公告通知(一定带链接)
				wxPartnerMessageService.sendSurveyNotice(notice.getEvaluateTitle(), notice.getEvaluateContent(), url, infoDto.getOpenId());
			} else if (3 == type) {
				//调用智杰祱公众号公告通知(一定带链接)
				wxTaxerWxMessageService.sendTaxerSurveyNotice(notice.getEvaluateTitle(), notice.getEvaluateContent(), url, infoDto.getOpenId());
			} else if (4 == type) {
				//调用智众包公众号公告通知(一定带链接)
				wxCrowdsourceMessageService.sendSurveyNotice(notice.getEvaluateTitle(), notice.getEvaluateContent(), url, infoDto.getOpenId());
			} else {
				LogUtil.error("评价公告通知-公众号通知类型不正确-openId：" + infoDto.getOpenId() + "-类型：" + type);
			}
		});
	}

	public SmartResult queryEvaluateNoticeList(BaseSimpleFormBean<QueryEvaluateNoticeFrombean> formBean){
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		QueryEvaluateNoticeFrombean queryFormBean = formBean.getReqdata();
		Date startDate = queryFormBean.getStartDate();
		if (null == startDate) {
			startDate = new Date(0);
		}
		Date endDate = queryFormBean.getEndDate();
		if (null == endDate) {
			endDate = new Date();
		}
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<EvaluateNotice> noticeList = evaluateNoticeMapper.queryEvaluateNoticeList(queryFormBean.getTitle(),startDate,endDate);
		return smartResult(noticeList,page.getTotal(), page.getPages(), page.getPageNum());
	}
}
